#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define BUFSIZE 1024

void error_handling(char *message) {
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

int main(int argc, char *argv[]) {
    int client_sock;
    if (argc != 3) {
        printf("Usage : %s <IP> <port>\n", argv[0]);
        exit(1);
    }
    if ((client_sock = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
        error_handling("socket() error!");
    }
    
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(argv[1]);
    server_addr.sin_port = htons(atoi(argv[2]));

    if (connect(client_sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        error_handling("connect() error!");
    } else {
        puts("connecting.......");
    }
    char ch;
    char buf[BUFSIZE];
    while (1) {
        fputs("input message (q to quit): \n", stdout);        
        fgets(buf, BUFSIZE, stdin);
        if (strcmp(buf, "q\n") == 0) 
            break;

        // 一次能否写完？？？
        // 是否需要循环写？
        write(client_sock, buf, strlen(buf));

        int len = read(client_sock, buf, BUFSIZE - 1);
        buf[len] = 0;
        printf("Message from server: %s\n", buf);
    }
    close(client_sock);
    return 0;
}